import os
import urllib2
import socket
import httplib
import json
import traceback
import time
import re
import pickle

def make_pricesheet():
    urls = ['http://dota2prices.com/couriers',
            'http://dota2prices.com/equipment',
            'http://dota2prices.com/sets',
            'http://dota2prices.com/stranges-modifiers',
            'http://dota2prices.com/tools-announcers-other'
            ]

    price_dict = {}

    for url in urls:        
        opener = urllib2.build_opener()
        grab = False
        lines = opener.open(url).readlines()    
        lines = "".join(lines)
        lines = re.sub('\n','',lines)
        lines = lines.split("Prices are listed in Treasure keys. Last edited by")[1]
        lines = lines.split("</tbody>")[0]
        lines = lines.split("</tr>")
        
        for line in lines:
            sub_line = line.split('</td>')
            if len(sub_line) == 8:
                name = sub_line[0].split(">")[-1]
                typeS = sub_line[1].split(">")[-1]
                effect = sub_line[2].split(">")[-1]                
                price = sub_line[5].split(">")[-1]
                contents = [typeS,effect,price]
                if not price_dict.has_key(name):
                    price_dict[name] = [contents]
                else:
                    price_dict[name].append(contents)
                    if url != 'http://dota2prices.com/couriers':
                        print 'name ',name , ' == ', contents
                    
    fp = open('pricelist.pkg','wb')
    pickle.dump(price_dict,fp)
    fp.close()
            
            
##make_pricesheet()

fp = open('pricelist.pkg','rb')
price_dict = pickle.load(fp)
fp.close()



steamID = '76561198085423307'

try:
    socket.setdefaulttimeout(40)
    conn = httplib.HTTPConnection('api.steampowered.com')

    conn.request('GET','/IEconItems_816/GetSchema/v0001/?language=en&key=YOURAPIKEY')
    r2 = conn.getresponse()
    schemaResult = json.loads(r2.read())['result']
    conn.close()

    itemSchemas = schemaResult['items']
##    print schemaResult['attributes']
##    print schemaResult['attribute_controlled_attached_particles']
##    for part in schemaResult['attribute_controlled_attached_particles']:
##        if part['name'].lower().find('divine') > -1:
##            print part
        
    socket.setdefaulttimeout(40)
    conn = httplib.HTTPConnection('api.steampowered.com')
    conn.request('GET', '/IEconItems_570/GetPlayerItems/v0001/?language=en&key=DC0ABC461EDD51716F0B7F9836A9FB46&SteamID=%s' % steamID)
    r2 = conn.getresponse()
    bp = json.loads(r2.read())['result']['items']
    for item in bp:        
        itemN = None
        for i in itemSchemas:
            if i['defindex'] == item['defindex']:
                itemN = i
                break
        if itemN != None:# and itemN['name'].lower().find('morok') > -1:
##        if item['quality'] == 3: #unusual
            #find the particle
            found = False
            particleName = None
            color = None
            if item.has_key('attributes'):
                for attr in item['attributes']:
                    if attr['defindex'] == 134: #means particle
                        if not found:
                            for part in schemaResult['attribute_controlled_attached_particles']:
                                if part['id'] == attr['float_value']:
                                    found = True
                                    particleName = part
                                    break
                    if attr['defindex'] == 142: #means color
                        p = 0
##                        print 'found'
                        
##            print '**defindex ',item['defindex'] , " name ", itemN#['name']
##            print '**defindex ',item['defindex'] , " name ", item
##            print particleName
            itemName = itemN['name']
            itemPrice = None
            for priceName in price_dict.keys():
                loops = price_dict[priceName]
                for loop in loops:
                    typeS,effect,price = loop
                    if item['quality'] == 3 and particleName != None:
                        if str(priceName.lower().strip()) == str(itemName.lower().strip()) and str(effect.lower().strip()) == str(particleName['name'].lower().strip()):
                            itemPrice = price
                            break
                    elif str(priceName.lower().strip()) == str(itemName.lower().strip()) and str(effect.lower().strip()) == '-':
                        itemPrice = price
                        break
##            print 'item ', itemName ,' ', item ,' price = ',itemPrice
            itemNameF = itemName
            if particleName != None:
                itemNameF+=' Effect:' +particleName['name']
            print 'item ', itemNameF ,' price = ',itemPrice
                             
            
    conn.close()   

except:
    print traceback.format_exc()
